﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://www.codeplex.com/EmlenMud

using BrainTechLLC.ThreadSafeObjects;

#if NO_SILVERLIGHT

using LinFu.AOP.Interfaces;
using System.Collections.Generic;
using System.Reflection;

#endif

namespace BrainTechLLC
{    
    public interface IPropertyChangeTracker
    {
        void RecordPropChanged(PropertyInfo propInfo, object oldVal, object newVal, IInvocationContext context);
    }

    public class PropertyChangeTracker<T> : IPropertyChangeTracker
        where T : class, new()
    {
        public ThreadSafeLookupOnDemand<string, PropertyChangeCollection<T>> PropertyChanges = new ThreadSafeLookupOnDemand<string, PropertyChangeCollection<T>>();

        public void RecordPropChanged(PropertyInfo propInfo, object oldVal, object newVal, IInvocationContext context)
        {
            string propName = propInfo.Name;
            PropertyChangeCollection<T> change = PropertyChanges.Get(propName);
            change.RecordChange(new PropertyChangeNotificationArgs(propInfo.Name, oldVal, newVal));
        }

        public void ResetPropertyChanges()
        {
            PropertyChanges.Lookup.Clear();
        }

        public void RevertChangesToLastReset(T item)
        {
            List<PropertyChangeCollection<T>> changes = PropertyChanges.AllItems;
            changes.ForEach(change => change._propertyDescriptor.SetValue(item, change._originalValue));
            PropertyChanges.Lookup.Clear();
        }
    }
}